#include <stdio.h>
#include <termios.h>
#include <fcntl.h>
#include <string.h>
#include <ctype.h>
#include <sys/unistd.h>


#define ASK         "Do you want another transaction"
#define TRIES       3           // max tries
#define SLEEPTIME   2           // time per try
#define BEEP        putchar('\a')   // alert user                                

int get_ok_char()
{
    int c;

    while ((c = getchar()) != EOF && strchr("yYnN",c) == NULL);

    return c;
}

int get_response(char *question,int maxtries)
{
    printf("%s (y/n)?\n",question);
    fflush(stdout);

    while (1) {
        int input;
        sleep(SLEEPTIME);
        input = tolower(get_ok_char());

        switch(input) {
            case 'y':return 0;
            case 'n':return 1;
        }
        if (maxtries-- == 0) {
            return 2;
        }
        BEEP;
    }
}


int tty_mode(int how)
{
    static struct termios original_mode;
    static int original_flags;

    if (how == 0) {
        tcgetattr(0,&original_mode);
        original_flags = fcntl(0,F_GETFL);
    }
    else{
        tcsetattr(0,TCSANOW,&original_mode);
        fcntl(0,F_SETFL,original_flags);
    }
    return 0;
}

int set_cr_noecho_mode()
{
    struct termios ttystate;

    tcgetattr(0,&ttystate);

    ttystate.c_lflag &= ~ICANON;    // no buffering
    ttystate.c_lflag &= ~ECHO;      // no echo either
    ttystate.c_cc[VMIN] = 1;        // get 1 char at a time
    tcsetattr(0,TCSANOW,&ttystate);
    return 0;
}

int set_nodelay_mode()
{
    int tempflags;
    tempflags = fcntl(0,F_GETFL);   // read curr setting
    tempflags |= O_NDELAY;          // flip the nodelay bit
    fcntl(0,F_SETFL,tempflags);     // and inistall 

    return 0;
}

int main()
{
    int response;

    tty_mode(0);
    set_cr_noecho_mode();
    set_nodelay_mode();
    response = get_response(ASK,TRIES);
    tty_mode(1);
    return response;
}

